<script setup lang="ts">
import { IconFont } from '@nutui/icons-vue-taro';
import { useAuthStore } from '@/store';
import { storeToRefs } from 'pinia';
import { reactive, ref, watch, computed, onMounted, onUnmounted } from 'vue';
import { useLogout, useImage } from '@/hooks';
import Taro from '@tarojs/taro';
import { request } from '@/service/request';
import { showModal } from '@tarojs/taro'
import { localStg, PlatformUtils } from '@/utils';
import { AppName } from '@/constants'
import { Popup, Picker } from '@nutui/nutui-taro'
import { getNurseUserFamilyList } from '@/service/api/nurse_user'
import ren from '@/assets/img/ren.png'

// import { IconFont } from '@nutui/icons-vue-taro'

const { nurseUser, curFamily } = storeToRefs(useAuthStore());
const authStore = useAuthStore();
const healthName = ref('管家');

// 检查登录状态的通用方法
const checkLoginStatus = () => {
  if (!authStore.isLogin) {
    Taro.showModal({
      title: '提示',
      content: '请先登录后再进行操作',
      confirmText: '去登录',
      cancelText: '取消'
    }).then((res) => {
      if (res.confirm) {
        // 跳转到登录页面
        Taro.navigateTo({
          url: '/pages/login/login'
        });
      }
    });
    return false;
  }
  return true;
};

// nurseUser

const CORPID = 'wweb2e9977cf9d5076' // 企业ID
// const CONFIG_ID = '1234567890123456' // 客服配置ID
// defaultHospital
const isHuaSheng = ref(PlatformUtils.isHuaSheng());

const curCodeData = ref<any>({});

// 被监护人切换相关状态
const showFamilyPicker = ref(false);
const familyPickerData = ref<any[]>([]);

// 初始化家庭数据
const initFamilyData = async () => {
  try {
    // 开始初始化家庭数据
    
    // 如果已经有家庭数据，直接使用
    if (nurseUser.value.nurseUserFamilyList && nurseUser.value.nurseUserFamilyList.length > 0) {
      // 使用现有家庭数据
      updateFamilyData(nurseUser.value.nurseUserFamilyList);
      return;
    }
    
    // 如果没有家庭数据，从API获取
    // if (nurseUser.value.id) {
    //   从API获取家庭数据，用户ID
    //   const { error, success } = await getNurseUserFamilyList(nurseUser.value.id);
    //   API返回结果
      
    //   if (!error && success?.records) {
    //     // 更新store中的家庭数据
    //     nurseUser.value.nurseUserFamilyList = success.records;
    //     更新家庭数据 (records)
    //     updateFamilyData(success.records);
    //   } else if (!error && Array.isArray(success)) {
    //     // 如果返回的是直接数组
    //     nurseUser.value.nurseUserFamilyList = success;
    //     更新家庭数据 (array)
    //     updateFamilyData(success);
    //   } else {
    //     没有获取到家庭数据
    //   }
    // } else {
    //   用户ID不存在，无法获取家庭数据
    // }
  } catch (error) {
    // 获取家庭成员数据失败
  }
};

// 更新家庭数据的通用方法
const updateFamilyData = (familyList: any[]) => {
  // 更新家庭数据
  
  if (familyList && familyList.length > 0) {
    // 检查是否已经有选中的家庭成员
    let selectedFamily = curFamily.value;
    
    // 如果没有选中的家庭成员，或者选中的家庭成员不在当前列表中，则选择第一个
    if (!selectedFamily || !familyList.find(f => f.id === selectedFamily?.id)) {
      selectedFamily = familyList[0];
      authStore.setCurFamily(selectedFamily);
      // 设置默认选中的家庭成员
    }
    
    // 更新显示的被监护人信息
    if (selectedFamily) {
      otherInfo.value = `被监护人: ${selectedFamily.name || ''}・${selectedFamily.sex === '1' ? '男' : '女'}・${selectedFamily.age || 20}${selectedFamily.ageUnit || '岁'}`;
      // 设置被监护人信息
    }
    localStg.set("curFamily", selectedFamily);
    // console.log('otherInfo====', selectedFamily)
    // 设置被监护人信息
    
    // 更新专家模块的列数据
    expertModule.columns = familyList.map(i => {
      return {
        ...i,
        text: i.name,
        value: i.id
      };
    });
    // 更新picker列数据
  } else {
    // 家庭数据为空，无法更新
  }
};

onMounted(() => {
  // healthCard 组件已挂载
  
  changeCode();
  initFamilyData();
})

// 使用医院事件监听组合式函数
import { useCustomHospitalEvent } from '@/composables/useHospitalEvent';

// 医院变化事件处理函数
const handleHospitalChange = (data: any) => {
    // 医院发生变化
    // 重新请求数据
    setTimeout(() => {
        changeCode();
    }, 100);
};

// 使用自定义医院事件监听
useCustomHospitalEvent(handleHospitalChange);

// 页面显示时重新请求数据（从机构切换页面返回时）
Taro.useDidShow(() => {
  // 页面显示，重新请求healthCard数据
  changeCode();
  isHuaSheng.value = PlatformUtils.isHuaSheng();
});

const changeCode = () => { 
  request.get('/wechatwork_code/wechatworkCode/list', {
    pageSize: 600
  }, {
    useErrMsg: true
  }).then((res: any) => {
    // res
    const sys_org_code = localStg.get('sys_org_code') || '';
    // sys_org_code
    res.success?.records?.forEach((item: any) => {
      // item
      if(item.sysOrgCode == sys_org_code){
        curCodeData.value = item;
        healthName.value = item.healthName;
      }
    }) || {};
    // curCodeData
  })
}

// 监听家庭成员列表变化
watch(
  () => nurseUser.value.nurseUserFamilyList,
  newVal => {
    if (newVal && newVal.length > 0) {
      // 家庭成员列表变化
      updateFamilyData(newVal);
    }
  },
  { deep: true }
);

// 监听当前选中的家庭成员变化
watch(
  () => curFamily.value,
  newVal => {
    if (newVal && nurseUser.value.nurseUserFamilyList && nurseUser.value.nurseUserFamilyList.length > 0) {
      // 当前选中的家庭成员变化，使用 updateFamilyData 方法统一更新
      updateFamilyData(nurseUser.value.nurseUserFamilyList);
    }
  },
  { deep: true }
);


// 监听医院机构切换，重新请求数据
watch(
  () => [
    nurseUser.value.defaultHospital,
    nurseUser.value.defaultHospitalName,
    localStg.get('sys_org_code')
  ],
  ([newDefaultHospital, newDefaultHospitalName, newSysOrgCode], [oldDefaultHospital, oldDefaultHospitalName, oldSysOrgCode]) => {

    // 检查是否发生了变化
    const hospitalChanged = newDefaultHospital !== oldDefaultHospital || newDefaultHospitalName !== oldDefaultHospitalName;
    const orgCodeChanged = newSysOrgCode !== oldSysOrgCode;
    
    if (hospitalChanged || orgCodeChanged) {
      // 检测到医院机构变化，重新请求数据
      // 延迟一下再请求，确保数据更新完成
      setTimeout(() => {
        changeCode();
      }, 100);
    }
  },
  { deep: true }
);

const mylist = computed(() => {
  return nurseUser.value.nurseUserFamilyList?.map(i => {
    return {
      ...i,
      text: i.name,
      value: i.id
    };
  }) || [];
});

const otherInfo = ref('被监护人・男・10岁');

// 格式化被监护人信息显示（直接使用，因为已经是正确格式）
const formattedGuardianInfo = computed(() => {
  return otherInfo.value || '被监护人';
});
const showHealthRolePopup = ref(false);

const toHealthCard = () => {
  // 检查登录状态
  if (!checkLoginStatus()) {
    return;
  }
  
  if (!useAuthStore().isRegistered) {
    showModal({
      title: '提示',
      content: isHuaSheng.value ? '您未注册健康码，请先注册。' :  '您未注册诊疗卡，请先注册。',
      confirmText: '去注册',
      cancelText: '取消'
    }).then((res) => {
      if (res.confirm) {
        toHealthCode();
      }
    });
    return;
  } 
  Taro.navigateTo({
    url: '/package-other/health/index'
  });
};

const toHealthCode = () => {
  // 检查登录状态
  if (!checkLoginStatus()) {
    return;
  }
  
  Taro.navigateTo({
    url: '/package-my/healthcode/index'
  });

};

const toCallCenter = () => {
  // 检查登录状态
  if (!checkLoginStatus()) {
    return;
  }
  
  if(!curCodeData.value.nurseCode){
    Taro.showToast({
      title: '请配置该机构护士专家',
      icon: 'none'
    })
    return
  }
  let weixin = useImage(curCodeData.value.nurseCode);
  Taro.previewImage({
    urls: [weixin],
    current: 0
  })
};

const expertModule: any = reactive({
  show: false,
  columns: nurseUser.value.nurseUserFamilyList?.map(i => {
    return {
      ...i,
      text: i.name,
      value: i.id
    };
  }) || [],
  // showExpert: () => {
  //   if (props.isOrder) return
  //   expertModule.show = !expertModule.show;
  // },
  confirm: ({ selectedValue, selectedOptions }: any) => {
    // 选中的家庭成员
    const selectedFamily = selectedOptions[0];
    // console.log("选中的家庭成员", selectedFamily)
    
    if (selectedFamily && nurseUser.value.nurseUserFamilyList && nurseUser.value.nurseUserFamilyList.length > 0) {
      // 保存选中的家庭成员到 curFamily
      authStore.setCurFamily(selectedFamily);
      
      // 使用 updateFamilyData 方法统一更新被监护人信息
      updateFamilyData(nurseUser.value.nurseUserFamilyList);
      
      // 已保存选中的家庭成员到 curFamily
    }
    
    expertModule.show = false;
  },
  setList: async () => {
    // const { error, success } = await getExpertList();
    // if (!error && success?.records) {
    //   const options = success?.records.map((item: any) => {
    //     if (item.sorts == '1' && !props.isOrder) {
    //       props.formData.expertId = item.id;
    //       props.formData.expertName = `${item.name}`;
    //       props.formData.expertFee = item.fee;
    //     }
    //     return { text: `${item.name}(￥${item.fee})`, name: item.name, value: item.id, fee: item.fee };
    //   });
    //   expertModule.columns = [{ text: '', value: '', fee: 0 }, ...options];
    // }
  }
});

// 监听 expertModule.show 的变化
watch(
  () => expertModule.show,
  (newVal, oldVal) => {
    // expertModule.show 变化
  }
);

// const showPickUser = ref(false);

const changeUser = () => {
  // changeUser 函数被调用
  console.log('changeUser',nurseUser.value.nurseUserFamilyList);
  
  // 检查登录状态
  if (!checkLoginStatus()) {
    // 登录状态检查失败，退出函数
    return;
  }

  if(nurseUser.value.isVerify != '1'){
    Taro.showToast({
      title: '请先进行认证',
      icon: 'none'
    })
    return;
  }
  
  // 登录状态检查通过
  
  // 检查是否有家庭成员数据
  if (!nurseUser.value.nurseUserFamilyList || nurseUser.value.nurseUserFamilyList.length === 0) {
    // 没有家庭成员数据，显示提示
    Taro.showToast({
      title: '暂无家庭成员数据',
      icon: 'none'
    });
    return;
  }
  
  // 准备显示picker，设置 expertModule.show = true
  expertModule.show = true;
  // expertModule.show 设置后值
};

const toHistory = () => {
  // Taro.navigateTo({
  //   url: '/pages/cloud-test/index'
  // });
  Taro.showToast({
    title: '暂未开发',
    icon: 'none'
  })
};

const toHealthRole = () => {
  // 检查登录状态
  if (!checkLoginStatus()) {
    return;
  }
  
  let weixin = '';
  if(!curCodeData.value.healthCode){
    Taro.showToast({
      title: '请配置该机构健康管家',
      icon: 'none'
    })
    return
  }
  weixin = useImage(curCodeData.value.healthCode);
  
  // if(isHuaSheng.value){
  //   weixin = 'https://anfine.huasun-healthcare.com/kefu/manager.png';
  // }
  // else{
  //   weixin = 'https://anfine.huasun-healthcare.com/kefu/manager-fine.png';
  // }

  Taro.previewImage({
    urls: [weixin],
    current: 0
  })
};
</script>

<template>
  <view class="m-auto w-340px p-[12rpx] rounded-[20rpx] shadow-md border border-[#A7F3D0]/30" style="background: linear-gradient(135deg, #D1FAE5 0%, #ECFDF5 100%);">

    <!-- 设计卡片 -->
    <view class="relative rounded-[20rpx] overflow-hidden border border-white/50" style="background: linear-gradient(135deg, #10B981 0%, #059669 100%);">
      <!-- 顶部区域 -->
      <view class="pb-[16rpx] px-[20rpx] pt-[20rpx]">
        <view class="flex items-start justify-between mb-[16rpx]">
          <!-- 左侧：用户信息 -->
          <view class="flex items-start flex-1">
            <view class="relative mr-[16rpx]">
              <view class="w-[100rpx] h-[100rpx] rounded-full flex items-center justify-center border-2 border-white/40" style="background: rgba(255, 255, 255, 0.25);">
                <image class="w-[84rpx] h-[84rpx] rounded-full bg-white/60" mode="aspectFill" :src="useImage(nurseUser.avatar || ren)" />
              </view>
            </view>
            <view class="flex-1 pt-[4rpx]">
              <view class="flex items-center gap-[6rpx] mb-[8rpx]">
                <text class="text-[32rpx] text-white font-bold">{{ nurseUser.name }}</text>
                <view class="flex items-center gap-[4rpx] px-[8rpx] py-[2rpx] rounded-[6rpx]" style="background: #3e4fa7;">
                  <IconFont font-class-name="iconfont" class-prefix="icon" name="dengji1" size="10" color="#fff"/>
                  <text class="text-[20rpx] text-white font-medium">{{ nurseUser.level || '1' }}</text>
                </view>
              </view>
              <view class="cursor-pointer active:opacity-80 flex items-center gap-[6rpx]" @tap="changeUser">
                <text class="text-[26rpx] text-white/95">{{ formattedGuardianInfo }}</text>
                <IconFont font-class-name="iconfont" class-prefix="icon" name="qiehuan" size="18" color="#fff"/>
              </view>
            </view>
          </view>
          
          <!-- 右侧：诊疗卡/健康码 -->
          <view class="flex flex-col items-end pt-[4rpx] cursor-pointer active:opacity-80" @click="toHealthCode">
            <view class="w-[60rpx] h-[60rpx] mb-[6rpx] flex items-center justify-center rounded-[12rpx] border border-white/30" style="background: rgba(255, 255, 255, 0.3);">
              <image class="w-[48rpx] h-[48rpx]" mode="aspectFit" src="@/assets/img/ewm.png" />
            </view>
            <text class="text-[22rpx] text-white/95">{{ isHuaSheng ? '健康码' : '诊疗卡' }}</text>
          </view>
        </view>

        <!-- 账户信息 -->
        <view class="flex items-center pt-[16rpx] border-t border-white/30">
          <!-- 兑换券 -->
          <view class="flex-1 flex flex-col items-center cursor-pointer active:opacity-80" @click="changeUser">
            <text class="text-[28rpx] text-white font-bold mb-[6rpx]">0张</text>
            <view class="flex items-center gap-[4rpx]">
              <IconFont font-class-name="iconfont" class-prefix="icon" name="youhuiquan" size="20" color="#fff"/>
              <text class="text-[24rpx] text-white/90">兑换券</text>
            </view>
          </view>

          <!-- 分隔线 -->
          <view class="w-[1rpx] h-[50rpx] bg-white/30"></view>

          <!-- 积分 -->
          <view class="flex-1 flex flex-col items-center">
            <text class="text-[28rpx] text-white font-bold mb-[6rpx]">0分</text>
            <view class="flex items-center gap-[6rpx]">
              <IconFont font-class-name="iconfont" class-prefix="icon" name="bonus-line" size="18" color="#fff"/>
              <text class="text-[24rpx] text-white/90">积分</text>
            </view>
          </view>
          
          <!-- 分隔线 -->
          <view class="w-[1rpx] h-[50rpx] bg-white/30"></view>
          
          <!-- 账户余额 -->
          <view class="flex-1 flex flex-col items-center">
            <text class="text-[28rpx] text-white font-bold mb-[6rpx]">¥0.00</text>
            <view class="flex items-center gap-[6rpx]">
              <IconFont font-class-name="iconfont" class-prefix="icon" name="yue" size="15" color="#fff"/>
              <text class="text-[24rpx] text-white/90">账户余额</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 功能按钮区域 -->
    <view class="mt-[16rpx] grid grid-cols-4 gap-[8rpx] bg-[#d4f3d6] rounded-[16rpx] p-[8rpx] border border-[#D1FAE5]/50">
      <!-- 健康档案 -->
      <view class="rounded-[12rpx] p-[16rpx] cursor-pointer active:opacity-80 bg-white/60 hover:bg-white/80 transition-all" @click="toHealthCard">
        <view class="flex flex-col items-center">
          <view class="w-[44rpx] h-[44rpx] mb-[6rpx] flex items-center justify-center rounded-[8rpx]">
            <IconFont font-class-name="iconfont" class-prefix="icon" name="jiankangdangan" size="22" color="#059669"/>
          </view>
          <text class="text-[22rpx] text-[#047857] font-medium">健康档案</text>
        </view>
      </view>

      <!-- 健康管家 -->
      <view class="rounded-[12rpx] p-[16rpx] cursor-pointer active:opacity-80 bg-white/60 hover:bg-white/80 transition-all" @click="toHealthRole">
        <view class="flex flex-col items-center">
          <view class="w-[44rpx] h-[44rpx] mb-[6rpx] flex items-center justify-center rounded-[8rpx]">
            <IconFont font-class-name="iconfont" class-prefix="icon" name="ren" size="20" color="#3B82F6"/>
          </view>
          <text class="text-[22rpx] text-[#047857] font-medium">健康管家</text>
        </view>
      </view>

      <!-- 专属服务群 -->
      <view class="rounded-[12rpx] p-[16rpx] cursor-pointer active:opacity-80 bg-white/60 hover:bg-white/80 transition-all" @click="toCallCenter">
        <view class="flex flex-col items-center">
          <view class="w-[44rpx] h-[44rpx] mb-[6rpx] flex items-center justify-center rounded-[8rpx]">
            <IconFont font-class-name="iconfont" class-prefix="icon" name="qiyeweixin" size="22" color="#6366F1"/>
          </view>
          <text class="text-[22rpx] text-[#047857] font-medium">专属服务群</text>
        </view>
      </view>
      
      <!-- 历史记录 -->
      <view class="rounded-[12rpx] p-[16rpx] cursor-pointer active:opacity-80 bg-white/60 hover:bg-white/80 transition-all" @click="toHistory">
        <view class="flex flex-col items-center">
          <view class="w-[44rpx] h-[44rpx] mb-[6rpx] flex items-center justify-center rounded-[8rpx]">
            <IconFont font-class-name="iconfont" class-prefix="icon" name="weixin" size="24" color="#059669"/>
          </view>
          <text class="text-[22rpx] text-[#047857] font-medium">历史记录</text>
        </view>
      </view>
    </view>
    <!-- <nut-popup v-model:visible="showPickUser" :style="{ padding: '30px 50px' }">正文</nut-popup> -->
    <nut-popup 
      v-model:visible="expertModule.show" 
      position="bottom"
      safe-area-inset-bottom
      :style="{ paddingBottom: '120rpx' }"
    >
      <nut-picker 
        :columns="mylist" 
        :default-value="curFamily?.id ? [curFamily.id] : []"
        title="选择被监护人" 
        @cancel="expertModule.show = false"
        @confirm="expertModule.confirm" 
      />
    </nut-popup>
    
    <!-- 健康管家二维码弹窗 -->
    <nut-popup v-model:visible="showHealthRolePopup" position="center" :style="{ padding: '40rpx' }">
      <view class="relative bg-white rounded-lg p-[30rpx]">
        <!-- 关闭按钮 -->
        <view 
          class="absolute top-0 right-0 w-[30rpx] h-[30rpx] flex items-center justify-center cursor-pointer"
          @click="showHealthRolePopup = false"
        >
          <IconFont name="close" size="20" color="#999"></IconFont>
        </view>
        
        <view class="flex flex-col items-center">
          <image 
            class="w-[400rpx] h-[400rpx] mb-[20rpx]" 
            src="https://anfine.huasun-healthcare.com/api/sys/common/static/temp/30_1754033053305.jpg" 
            mode="aspectFit" 
            show-menu-by-longpress
          />
          <text class="text-[28rpx] text-gray-700 text-center">长按联系你的健康管家！</text>
        </view>
      </view>
    </nut-popup>
  </view>
</template>

<style scoped>
.coo {
  color: #0667f8;
}
</style>